package com.example.es.service;

import com.example.es.entity.UsrDoc;
import com.example.es.repo.UsrRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UsrService {

    private final UsrRepository repo;

    /* ---------- 增 ---------- */
    public UsrDoc save(UsrDoc doc) {
        return repo.save(doc);
    }

    /* ---------- 删 ---------- */
    public void deleteById(String usrId) {
        repo.deleteById(usrId);
    }

    /* ---------- 改 ---------- */
    public UsrDoc update(UsrDoc doc) {
        // Spring Data 的 save 根据 @Id 存在即覆盖
        return repo.save(doc);
    }

    /* ---------- 查 ---------- */
    public Optional<UsrDoc> findById(String usrId) {
        return repo.findById(usrId);
    }

    public Page<UsrDoc> findAll(Pageable pageable) {
        return repo.findAll(pageable);
    }

    /* 年龄 + 日期区间 */
    public Page<UsrDoc> search(Integer ageFrom, Integer ageTo, String dateFrom, String dateTo, Pageable pageable) {
        return repo.searchByAgeAndJoinDate(ageFrom, ageTo, dateFrom, dateTo, pageable);
    }

    /* 附加：再模糊姓名 */
    public Page<UsrDoc> search(Integer ageFrom, Integer ageTo, String dateFrom, String dateTo, String name, Pageable pageable) {
        return repo.searchByAgeAndJoinDateAndName(ageFrom, ageTo, dateFrom, dateTo, name, pageable);
    }

    /**
     * 根据Age范围进行查询-自己写
     */
    public Page<UsrDoc> searchByAge1(Integer min, Integer max, Pageable pageable) {
        return repo.searchByAgeRange1(min, max, pageable);
    }

    /**
     * 根据Age范围进行查询-SpringData
     */
    public Page<UsrDoc> searchByAge2(Integer min, Integer max, Pageable pageable) {
        return repo.findByUsrAgeBetween(min, max, pageable);
    }
}